import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Users from '@/components/user/Users.vue'
import Rights from '@/components/power/Rights.vue'
import Roles from '@/components/power/Roles.vue'
import Cate from '@/components/goods/Cate.vue'
import Params from '@/components/goods/Params.vue'
import Goods from '@/components/Goods.vue'
import Welcome from '@/components/Welcome.vue'
import Error from '@/components/404.vue'

Vue.use(VueRouter)

const routes = [

  { path: '*', name: '404', component: Error },
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, name: 'Login' },
  {
    path: '/home',
    component: Home,
    name: 'Home',
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome, name: 'Welcome' },
      { path: '/users', component: Users, name: 'Users' },
      { path: '/rights', component: Rights, name: 'Rights' },
      { path: '/roles', component: Roles, name: 'Roles' },
      { path: '/goods', component: Goods, name: 'Goods' },
      { path: '/categories', component: Cate, name: 'Cate' },
      { path: '/params', component: Params, name: 'Params' }
    ]
  }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const tokonStr = window.sessionStorage.getItem('token')
  if (to.path === '/login') {
    if (tokonStr) return next('/home')
    return next()
  }

  if (!tokonStr) return next('/login')

  next()
})

export default router
